package com.audio.main;

import java.io.FileDescriptor;
import java.nio.charset.CharsetEncoder;

import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.SoundPool;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidAudioDevice {

	AudioTrack track;
	byte[] buffer = new byte[1024];
	boolean flagStop = true;
	TextView sample = null;
	TextView state = null;
	AudioManager mAudioManager;
	Context mContext;
	SoundPool mSoundPool;

	public AndroidAudioDevice(int bufferSize, TextView sample, TextView state,
			Context mContext) {

		this.initComponents(mContext);
		this.sample = sample;
		this.state = state;

		int minSize = AudioTrack.getMinBufferSize(22050,
				AudioFormat.CHANNEL_CONFIGURATION_MONO,
				AudioFormat.ENCODING_PCM_16BIT);
		track = new AudioTrack(AudioManager.STREAM_VOICE_CALL, 22050,
				AudioFormat.CHANNEL_CONFIGURATION_MONO,
				AudioFormat.ENCODING_PCM_16BIT, minSize, AudioTrack.MODE_STREAM);
		// track.setStereoVolume(100, 100);

		float streamVolume = mAudioManager
				.getStreamVolume(AudioManager.STREAM_VOICE_CALL);

		streamVolume = streamVolume
				/ mAudioManager
						.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);

		track.setStereoVolume(streamVolume, streamVolume);
		// track.setPlaybackRate(29000);

		track.play();
	}

	public void initComponents(Context mContext) {
		this.mContext = mContext;
		mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
		mAudioManager = (AudioManager) mContext
				.getSystemService(Context.AUDIO_SERVICE);
	}

	public void writeSamples(float[] samples) {
		// fillBuffer(samples);
		track.write(buffer, 0, samples.length);
	}

	public void writeSamples(byte data[], int bufferSize, boolean flag) {
		float streamVolume = mAudioManager
		.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
		
		while (flagStop) {
			//fillBuffer(data);
			try {
				//track.wait(5000);				

			} catch (Exception e) {
				// TODO: handle exception
			}
			
			track.write(data, 0, data.length);
//			FileDescriptor file = new FileDescriptor();
//			mSoundPool.load(file, 0, data.length, 1);
//			mSoundPool.play(1, streamVolume, streamVolume, 1, -1, 1f);


			// buffer = new short[bufferSize];
			// track.flush();
		}
	}

	public void writeSamples(int bufferSize) {
		track.write(buffer, 0, bufferSize);
	}

	public void deviceStop() {
		flagStop = false;
		track.stop();
	}

	private void fillBuffer(byte[] samples) {
		if (buffer.length < samples.length)
			buffer = new byte[samples.length];

		for (int i = 0; i < samples.length; i++)
			buffer[i] = (byte) (samples[i] * Short.MAX_VALUE);
	}

}
